import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { message } from 'ant-design-vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'HomePage',
      component: () => import('@/pages/HomePage.vue'),
    },
    {
      path: '/document',
      name: 'DocumentPage',
      component: () => import('@/pages/DocumentPage.vue'),
    },
    {
      path: '/user/login',
      name: 'UserLoginPage',
      meta: {
        layout: 'pull'
      },
      component: () => import('@/pages/user/UserLoginPage.vue'),
    },
    {
      path: '/admin/user-manage',
      name: 'UserManagePage',
      meta: {
        requiresAdmin: true
      },
      component: () => import('@/pages/admin/UserManagePage.vue'),
    },
    {
      path: '/user/agreement',
      name: 'UserAgreementPage',
      component: () => import('@/pages/user/UserAgreementPage.vue'),
    },
    {
      path: '/user/policy',
      name: 'PrivacyPolicyPage',
      component: () => import('@/pages/user/PrivacyPolicyPage.vue'),
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFoundPage',
      meta: {
        layout: 'pull'
      },
      component: () => import('@/pages/NotFound.vue'),
    }
  ],
})

// 路由守卫：检查管理员权限
router.beforeEach((to, from, next) => {
  // 如果路由需要管理员权限
  if (to.meta.requiresAdmin) {
    const userStore = useUserStore()
    // 检查用户是否为管理员
    if (userStore.loginUser.userRole !== 'admin') {
      message.warning('您没有权限访问此页面')
      next('/') // 重定向到首页
      return
    }
  }
  next()
})

export default router
